package org.cobaya.pages;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cobaya.commons.Assert;
import org.cobaya.commons.IO;
import org.tautua.markdownpapers.Markdown;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * Freemarker工具
 * 
 * @author lenic 2013-3-27
 * 
 */
public abstract class GithubPages {

	private static Log log = LogFactory.getLog(GithubPages.class);

	private static Configuration freemarker = new Configuration();

	static {
		try {
			File templates = IO.openFile(IO.PREFIX_USERDIR + "templates");
			freemarker.setDirectoryForTemplateLoading(templates);
		} catch (IOException e) {
			log.error("", e);
		}
		freemarker.setObjectWrapper(new DefaultObjectWrapper());
		freemarker.setDefaultEncoding(IO.UTF_8);
		freemarker.setEncoding(Locale.CHINA, IO.UTF_8);
		freemarker.setOutputEncoding(IO.UTF_8);
	}

	public static void freemarker(String ftl, File output) {
		freemarker(ftl, output, null);
	}

	public static void freemarker(String ftl, File output, Map<Object, Object> attributes) {
		try {
			Template template = freemarker.getTemplate(ftl, IO.UTF_8);
			template.setEncoding(IO.UTF_8);
			template.setOutputEncoding(IO.UTF_8);
			Writer writer = IO.openWriter(output);
			template.process(attributes, writer);
			IO.closeWriter(writer);
		} catch (Exception e) {
			log.error("process template[" + ftl + "] to [" + output + "] error", e);
		}
	}

	public static void markdown(File md, File output) {
		Assert.notNull(md, "mdFile must not be null");
		Assert.notNull(output, "output must not be null");
		try {
			Reader reader = IO.openReader(md);
			Writer writer = IO.openWriter(output);
			new Markdown().transform(reader, writer);
			IO.closeReader(reader);
			IO.closeWriter(writer);
		} catch (Exception e) {
			log.error("Markdown file [" + md + "] transfer to [" + output + "] error", e);
		}
	}

	public static String markdown(File md) {
		try {
			String path = "tmpdir:" + System.currentTimeMillis() + ".tmp";
			markdown(md, IO.openFile(path));
			return FileUtils.readFileToString(IO.openFile(path), IO.UTF_8);
		} catch (Exception e) {
			log.error("Markdown file [" + md + "] transfer to InputStream error", e);
			return null;
		}
	}
}